// pages/Order/OrderDetail/OrderDetail.js
//获取应用实例
const app = getApp();
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { queryTravelOrderForm , payTravelOrderForm } from '../../../api/travel';
import { queryTravelVehicleSafeConfig } from '../../../api/vehicle';
import { queryUserWechatOpenId , getUserAccount , getUser } from '../../../api/user';
const regeneratorRuntime = require('../../../common/runtime');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
    orderCode: '',
    order: {},
    showGoOnPay: false,
    balance: 0,
    openId: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.orderCode){
      this.setData({
        orderCode: options.orderCode,
      })
      this._getOrders();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 查询订单数据
  _getOrders(){
    let _this = this;
    queryTravelOrderForm({orderCode: _this.data.orderCode})
    .then(async (res) => {
      if(res.success){
        if(res.data.content.length > 0){
          const item = res.data.content[0];
          console.log(item,'item')
          item.info = JSON.parse(item.item);
          if(item.itemType != 3){
            item.info.titleImgUrlList = item.info.titleImgUrl.split(',');
          }else{
            item.info.vehicleInfo.instruction = item.info.vehicleInfo.instruction.replace(/,/g,'|');
            item.info.vehicleInfo.tagList = item.info.vehicleInfo.tag.split(',');
            let safeList = []
            for (let index = 0; index < item.info.safeguardInfo.length; index++) {
              const safe = item.info.safeguardInfo[index];
              let safeConfig = await _this._queryTravelVehicleSafeConfig({safeId: safe.id})
              if(safeConfig != '0'){
                safeList.push(safeConfig)
              }
            }
            item.info.safeguardConfig = safeList;
          }
          item.travelUser = JSON.parse(item.travelUser);
          if(item.status == '0'){
            _this.allData();
          }
          _this.setData({
            order: item,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取租车商家保障信息
  _queryTravelVehicleSafeConfig({safeId}){
    return new Promise((resolve,reject) => {
      queryTravelVehicleSafeConfig({id: safeId})
      .then(res => {
        if(res.success){
          if(res.data.content.length > 0){
            const element = res.data.content[0];
            let safeguardContentList = element.safeguardContent ? element.safeguardContent.replace(/\n/g,'#$%^&*()!@#').split('#$%^&*()!@#') : [];
            let list = [];
            for (let j = 0; j < safeguardContentList.length; j++) {
              const cont = safeguardContentList[j];
              let obj = {};
              if(cont.substring(0,5).indexOf('无需') != -1){
                obj.type = '1';
              }
              obj.cont = cont;
              list.push(obj);
            }
            element.safeguardContentList = list;
            resolve(element);
          }else{
            resolve('0')
          }
        }else{
          reject(res.errMessage);
        }
      })
    })
  },
  // 获取所有接口
  allData(){
    this._getUserAccount('0');
    this._queryUserWechatUnionId();
  },
  // 获取用户的Openid
  _queryUserWechatUnionId(){
    let _this = this;
    wx.login({
      success: (logRes) => {
        queryUserWechatOpenId({code: logRes.code})
        .then(res => {
          if(res.success){
            _this.setData({
              openId: res.data.openid
            })
          }else{
            wx.showToast({
              title: res.errMessage,
              icon: 'none',
            })
          }
        })
      }
    })
  },
  // 获取用户账户余额
  _getUserAccount(type){
    let _this = this;
    getUserAccount(type)
    .then(res => {
      if(res.success){
        if(type == 0){
          _this.setData({
            balance : res.data.balance,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none'
        })
      }
    })
  },
  // 去支付
  goPay(e){
    let _this = this;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    if(item.paidAmount > 0){
      // 如果之前是组合支付，那么继续支付就默认使用微信支付
      _this.pay({orderCode: item.orderCode,payType: 2,isMixPay: '1'});
    }else{
      _this.setData({
        showGoOnPay: true,
        payAmount: item.paymentPrice,
        payType: _this.data.balance < item.payAmount ? 2 : '0',
        goOnPayOrderCode: item.orderCode,
      })
    }
  },
  onClose(){
    this.setData({
      showGoOnPay: false,
    })
  },
  // 选择维信支付
  selWechatPay(e){
    let payType = e.target.dataset.type||e.currentTarget.dataset.type;
    this.setData({
      payType: payType,
    })
  },
  // 确认选择通道继续支付
  submitGoOnPay(){
    if(this.data.payType == '0'){
      if(this.data.payAmount > this.data.balance){
        // wx.showToast({
        //   title: '当前账户余额不足，请更换其他支付方式',
        //   icon: 'none',
        // })
        // return;
        wx.showModal({
          title: '温馨提示',
          content: '当前余额不足，是否前往充值？',
          success: (modal) =>{
            if(modal.confirm){
              wx.navigateTo({
                url: '/pages/Earnings/UpTopBalance/UpTopBalance',
                events: {
                  'updateUserAccount': function(){
                    this._getUserAccount('0');
                  },
                }
              })
            }
          },
        });
        return
      }
    }
    if(this.data.payType == '0'){
      const child = this.selectComponent('.pay-passwordAuth');
      child.clearPassword();
      child.openPayAuth();
    }else{
      this.pay({orderCode: this.data.goOnPayOrderCode,payType: this.data.payType});
    }
  },
  // 余额支付校验密码成功
  sonSubmitOrder(e){
    this.setData({
      payPassword: e.detail,
    })
    this.pay({orderCode: this.data.goOnPayOrderCode,payType: this.data.payType});
  },
  pay({orderCode,payType,isMixPay,}){
    let _this = this;
    payTravelOrderForm({payType: payType,orderCode: orderCode,openId: _this.data.openId,payPassword: _this.data.payType == '0' ? _this.data.payPassword : null}).then(res => {
      if(res.success){
        _this.wechatPay({payType: payType,wechatSign: res.data ? res.data.data : res.data});
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 支付
  wechatPay({payType,wechatSign}){
    let _this = this;
    if(payType == '0'){
      _this.setData({
        page: 0,
        isReachBottom: false,
        noMore: false,
        loading: false,
        loadingFailed: false,
        showGoOnPay: false,
      })
      _this._getUserAccount('0');
      _this._getOrders();
      wx.showToast({
        title: '支付成功',
        icon: 'success'
      })
    }else{
      console.log((wechatSign),'jsonData');
      var order = JSON.parse(wechatSign)
      // TODO微信支付
      wx.requestPayment({
        timeStamp: order.timeStamp.toString(),
        nonceStr: order.nonceStr,
        package: order.package,
        signType: order.signType,
        paySign: order.paySign,
        success: () => {
          _this.setData({
            page: 0,
            isReachBottom: false,
            noMore: false,
            loading: false,
            loadingFailed: false,
            showGoOnPay: false,
          })
          _this._getOrders();
          wx.showToast({
            title: '支付成功',
            icon: 'success'
          })
        },
        fail: (err) => {
          console.log(err,'err')
          wx.showToast({
            title: '取消支付',
            icon: 'none',
          })
        }
      })
    }
  },
})